package com.iflytek.uoamp.agent.monitor.lib;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.iflytek.uoamp.agent.core.sender.monitorsender.monitorinterface.IItem;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.MonitorItemResult;
import com.iflytek.uoamp.agent.monitor.mcagent.SendClient;
import com.iflytek.uoamp.agent.monitor.sender.config.Config;
import com.iflytek.uoamp.agent.monitor.sender.interfaces.ISenderFactory;

/**
 * @author gaowei
 * lib的发送客户端
 */
public class CreateSender implements ISenderFactory<SendClient>{
	@Override
	public SendClient createSender(String host, int port, Config config) {
		try {
			SendClient client = new SendClient();
			Logger.getRootLogger().info("Make a new sendClient to host : ".concat(host).concat(":").concat(String.valueOf(port)) );
			return client;
		} catch (Exception e) {
			Logger.getRootLogger().error(e.getMessage(),e);
			return null;
		}
	}
	
	@Override
	public IItem caseObject(String content) {
		String[] result = content.split(""+(char)31+(char)32+(char)31);
		try{
			Map<String, String> key = stringToMap(result[0]);
			if(result.length==2){
				return (IItem) new LibSendObj(key,ByteBuffer.wrap(result[1].replaceAll("5>//n<7", "\n").replaceAll("5>//r<7", "\r").getBytes("utf-8")));
			}else{
				return (IItem) new LibSendObj(key,ByteBuffer.wrap(new byte[0]));
			}
			
		}catch(Exception e){
			Logger.getRootLogger().error(e.getMessage(),e);
			MonitorItemResult temp;
			try {
				temp = MonitorItemResult.getFromByte(ByteBuffer.wrap(content.getBytes("utf-8")));
			} catch (UnsupportedEncodingException e1) {
				Logger.getRootLogger().error(e1.getMessage(),e1);
				temp = MonitorItemResult.getFromByte(ByteBuffer.wrap(content.getBytes()));
			}
			return temp;
		}
	}
	
	public Map<String, String> stringToMap(String header){
		String[] list = header.split((char)31+"");
		Map<String, String> result = new HashMap<String, String>();
		for(int i=0;i<list.length;i+=2){
			result.put(list[i], list[i+1].replaceAll("5>//n<7", "\n").replaceAll("5>//r<7", "\r"));
		}
		return result;
	}
}
